/**
 * 
 */
package cn.ad.server.web.servlet.v2.parser;

import cn.ad.server.web.spring.model.IAdserverRequest;
import cn.ad.server.web.spring.model.IAdserverResponse;
import cn.ad.server.web.spring.model.gdt.GDTBidRequest;
import cn.ad.server.web.spring.model.gdt.GDTBidResponse;
import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 广电通Bid 请求解析类
 * @author Wu Chengjun
 */
public class GTDBidServletParser extends HttpServletParserAdapter {

	private static final String CONTENT_TYPE_PROTOBUF = "application/x-protobuf;charset=utf-8";
	
	/**
	 * 
	 */
	public GTDBidServletParser() {
	}

	/* (non-Javadoc)
	 * @see cn.ad.server.web.servlet.parser.HttpServletParser#parse(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public IAdserverRequest parse(HttpServletRequest request) throws AdRequestParseException {
		GDTBidRequest bidRequest = null;
		try {
			Codec<GDTBidRequest> gdtBidRequestCodec = ProtobufProxy.create(GDTBidRequest.class);
			// bidRequest =
			// gdtBidRequestCodec.decode(request.getInputStream().toString().getBytes());
			CodedInputStream z = CodedInputStream.newInstance(request.getInputStream());
			bidRequest = gdtBidRequestCodec.readFrom(z);
		} catch (Exception e) {
			throw new AdRequestParseException(e);
		}
		return bidRequest;
	}

	/* (non-Javadoc)
	 * @see cn.ad.server.web.servlet.parser.HttpServletParser#writeResponse(cn.falconnect.adserver.adapter.AdResponse, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void writeResponse(IAdserverResponse adResponse, HttpServletResponse response) throws AdRequestParseException {
		response.setContentType(CONTENT_TYPE_PROTOBUF);
		response.setHeader("Connection", "Keep-Alive");
		Codec<GDTBidResponse> gdtBidResponseCodec = ProtobufProxy.create(GDTBidResponse.class);
		try {
			CodedOutputStream z = CodedOutputStream.newInstance(response.getOutputStream());
			gdtBidResponseCodec.writeTo((GDTBidResponse) adResponse, z);
			z.flush();
		} catch (IOException e) {
			throw new AdRequestParseException(e);
		}
	}

}
